package com.easy.system.dao.impl;

import com.easy.system.dao.ContextDao;
import com.easy.system.util.KeyValueDto;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sunguangzhu
 * Date: 13-6-18
 * Time: 下午1:20
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class ContextDaoImpl extends HibernateDaoSupport implements ContextDao {
    @Override
    public List<KeyValueDto> getKeyValueDtos(final String sql) throws SQLException {
        List<KeyValueDto> keyValueDtos = new ArrayList<KeyValueDto>();
        DataSource ds = SessionFactoryUtils.getDataSource(getSessionFactory());
        Connection connection = ds.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            KeyValueDto keyValueDto = new KeyValueDto();
            keyValueDto.setId(resultSet.getLong("id"));
            keyValueDto.setText(resultSet.getString("name"));
            keyValueDtos.add(keyValueDto);
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        return keyValueDtos;
        //To change body of implemented methods use File | Settings | File Templates.
    }

}
